<?php if ( ! defined('APPPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/

class share_controller extends PZ_Controller {

	public function __construct() {
		parent::__construct();
		$this->authfunctions = array('post','addlike','ajaxgetshare','removelike','delete'
				,'categoryhotshare','crophotshare','editshare','dtype','forwarding','collect');
	}

	public function index(){
		$this->output("share/index");
	}

	public function buy(){
		$item_id = $this->param("mid");
		if($item_id&&is_numeric($item_id)){
			$ptx_item = load_db('share/itemdetail');
			$item = $ptx_item->findbyid($item_id);
			if($item['promotion_url']){
				if(strpos($url, 'http://')===false||strpos($url, 'https://')===false){
					$url = pzxdecode($item['promotion_url']);
				}else{
					$url = str_ireplace('+', '%2B', $item['promotion_url']);
				}
				$this->jump($url);
				return;
			}else{
				$this->reflink = httpurl($item['reference_url']);
				$this->output('share/buy');
				return;
			}
		}

		$this->redirect(site_url(config_item('default_module')), lang('404_error_heading','tip'));
	}

	public function categoryhotshare(){
		if(!$this->isadmin&&!$this->iseditor){
			$this->ajax_failed_response(lang('illegal_operation','tip'));
		}
		$category_id = $this->param('cid');
		$sid = $this->param('sid');
		$results = load_db('category')->get_category_top();
		foreach ($results as $category) {
			if($category['category_id']==$category_id){
				$category['rand'] = random_string();
				$category['share_id'] = $sid;
				$this->ajax_success_response($category, '');
				return;
			}
		}
		
		$this->ajax_failed_response(lang('404_category_not_exist','tip'));
		return;
	}


	public function crophotshare(){
		if(!$this->isadmin&&!$this->iseditor){
			$this->ajax_failed_response(lang('illegal_operation','tip'));
		}
		$share_id = $this->param('sid');
		$category_id = $this->param('cid');

		if(!$category_id){
			$this->ajax_failed_response(lang('lost_param','tip'));
			return;
		}

		$position = $this->param("position");
		$x = $this->param("x");
		$y = $this->param("y");
		$w = $this->param("w");
		$h = $this->param("h");
		$js_w = $this->param("js_w");
		$js_h = $this->param("js_h");
		$ww = $this->param("ww");
		$hh = $this->param("hh");
		$style = $this->param("sy");

		$share = load_api('share')->getShareById($share_id);
		if($share){
			$imagelib = &load_class("ImageLib");
			$imagepath = thumburl($share['image_path_0'],'large',false,true);
			$homeimagepath = thumburl($share['image_path_0'],'home',false,true);
			load_api('event')->cropimagestart($imagepath,$share['cloud']);
			$image_size=getimagesize($imagepath);
			$weight=$image_size[0];
			$height=$image_size[1];
			if($js_w<$weight){
				$scale = $js_w/$weight;
			}elseif ($js_h<$height){
				$scale = $js_h/$height;
			}else{
				$scale = 1;
			}
			$x = $x/$scale;
			$y = $y/$scale;
			$w = $w/$scale;
			$h = $h/$scale;
			$imagelib->crop_image($imagepath,$homeimagepath,$x,$y,$w,$h);
			$imagelib->create_thumb($homeimagepath,NULL,$ww,$hh,$homeimagepath);
			load_api('event')->cropimageend($imagepath,$homeimagepath,$share['cloud']);
		}

		$categorydb = load_db('category');
		$category = $categorydb->find(array('category_id'=>$category_id));
		if($category&&$category_id){
			$shares = $category['category_home_shares']?unserialize($category['category_home_shares']):array();
			$shares['style'] = $style;
			$shares['s'.$position] = $share_id;
			$shares = serialize($shares);
			$categorydb->update(array('category_id'=>$category_id),array('category_home_shares'=>$shares));
			$categorydb->update_category_top();
			$data['img']= thumburl($share['image_path_0'],'home',$share['cloud']).'?'.uniqid();
			$this->ajax_success_response($data,lang('200_operatesuccess','tip'));
			return;
		}
		$this->ajax_failed_response(lang('500_operatefaild','tip'));
		return;
	}

	public function forwarding(){
		$albumid = $this->param('aid');
		$shareid = $this->param('sid');
		$category_id = $this->param('cid');
		if(!$albumid||!$shareid||!$category_id){
			$this->ajax_failed_response(lang('lost_param','tip'));
			return;
		}
		$sharedb = load_db('share');
		$share = $sharedb->getShareById($shareid);
		if($share['user_id'] == $this->cuser['uid']){
			$this->ajax_failed_response(lang('500_likeself','tip'));
			return;
		}

		$result = $sharedb->creat_forward($shareid,$category_id,$albumid,$this->cuser['uid'],$this->cuser['nickname']);

		if($result){
			$this->ajax_success_response(null, lang('200_operatesuccess','tip'));
		}else{
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
		}
	}


	public function ajaxgetshare(){
		if($shareid = $this->param('sid')){
			$shareapi = load_api('share');
			$share = $shareapi->getShareById($shareid);
			$share = $shareapi->prepareshare($share);
			$share['random'] = random_string(alnum,3);
			return $this->ajax_success_response(array('share'=>$share), lang('200_operatesuccess','tip'));
		}
	}

	public function editshare(){
		$act = $this->param('act');
		$shareid = $this->param('sid');
		$shareapi = load_api('share');
		$share = $shareapi->getShareById($shareid);
		if(!$this->iseditor&&!$this->isadmin&&$share['user_id'] != $this->cuser['uid']){
			$this->message(lang('nopermission','tip'),lang('nopermission','tip'));
			return;
		}
		if($act=='save'){
			$attapi = load_api('attachment');
			$attachesBefore = $attapi->findAttachByItem($share['item_id']);
			if($share){
				if(!$this->iseditor&&!$this->isadmin&&$share['user_id'] != $this->cuser['uid']){
					$this->ajax_failed_response(lang('illegal_operation','tip'));
					return;
				}
				if(($share['user_id']==$share['poster_id'])&&($share['poster_id']==$this->cuser['uid']||$this->iseditor||$this->isadmin)){

					$requiredParam = array('title','text','category_id','album_id');
					$shareSetting = $this->shareSetting;
					$titleminlenth=$shareSetting['title_range_s']?$shareSetting['title_range_s']:4;
					$titlemaxlength=$shareSetting['title_range_l']?$shareSetting['title_range_l']:100;
					$contentmaxlenth=$shareSetting['content_range_l']?$shareSetting['content_range_l']:10000;
					$fvalidation = load_class('Form_validation');
					foreach ($requiredParam as $rkey){
						if($rkey=='title'){
							$fvalidation->set_rules($rkey, 'lang:'.$rkey.':field' , 'trim|required|min_length['.$titleminlenth.']|max_length['.$titlemaxlength.']|xss_clean');
						}elseif($rkey=='text'){
							$fvalidation->set_rules($rkey, 'lang:'.$rkey.':field' , 'trim|max_length['.$contentmaxlenth.']|xss_clean');
						}else{
							$fvalidation->set_rules($rkey, 'lang:'.$rkey.':field' , 'trim|required|xss_clean');
						}
						$data[$rkey] = $this->param($rkey);
					}
					if ($fvalidation->run() == FALSE){
						$this->ajax_failed_response($fvalidation->error_string());
						return FALSE;
					}

					$optionalParam = array('price','keyword','url','uploadimgs','uploadfiles','videos','fetchs');
					foreach ($optionalParam as $okey){
						$data[$okey] = $this->param($okey);
					}

					$censorapi = load_api('censor');
					$txtresult = $censorapi->censor($data['text'],'***');
					if($txtresult){
						$this->ajax_failed_response($txtresult);
						return;
					}
					$titleresult = $censorapi->censor($data['title'],'***');
					if($titleresult){
						$this->ajax_failed_response($titleresult);
						return;
					}

					$data['item_id'] = $share['item_id'];
					$data['share_id'] = $shareid;
					if($this->prepareItem($data,true)){
						$results = array();
						$results[] = $this->processuploadimgs($data);
						$results[] = $this->processuploadfiles($data);
						$results[] = $this->processuploadvideos($data);
						$results[] = $fetchs = $this->processfetchs($data);
						$cover = array();
						$total = 0;
						$attacheidsafter = array();
						foreach ($results as $r){
							$total += $r['total'];
							if($r['findcover']){
								$cover = $r;
							}
							if(is_array($r['aids'])){
								$attacheidsafter = array_merge($attacheidsafter,$r['aids']);
							}
						}
						$cover['total'] = $total;
						if($fetchs['total']>0){
							$cover['remoteimgs'] = $fetchs['remoteimgs'];
						}

						foreach ($attachesBefore as $attachB){
							if(!in_array($attachB['aid'], $attacheidsafter)){
								$attapi->delAttachByAidAndItem($attachB['aid'],$share['item_id']);
							}
						}
						
						if(load_api('share')->updateItem($cover, $share['item_id'])){
							load_api('event')->aftereditshare($share);
							$attapi->deleteUnusedByUser($this->cuser['uid']);
							load_api('album')->update_album_cover($share['album_id']);
						}
						//$attachesafter = $attapi->findAttachByItem($share['item_id']);
						//$attacheidsafter = array();
						//$attacheSer = array();
						//foreach ($attachesafter as $key=>$attach){
						//	$attacheSer[$attach['aid']] = $attach;
						//	$attacheidsafter[] = $attach['aid'];
						//}

						$this->ajax_success_response(array('url'=>site_url('pin/index')),lang('200_postsuccess','tip'));
						return;
					}

				}else{
					$da['album_id'] = $this->param('aid');
					$da['category_id'] = $this->param('cid');
					load_db('share')->update(array('share_id'=>$shareid),$da);
					$this->ajax_success_response(null, lang('200_operatesuccess','tip'));
					return;
				}

			}
		}else{

			$this->shareid = $shareid;
			$this->share = $share;
			
			$api = load_api('setting');
			$uploadSetting = $api->getSetting('upload');
			$this->allowmaxnum = ($this->memperm['maxattachnum']&&!$this->isadmin&&!$this->iseditor)?$this->memperm['maxattachnum']:$uploadSetting['allow_max_num'];
			$this->maxattachsize = ($this->memperm['maxattachsize']&&!$this->isadmin&&!$this->iseditor)?$this->memperm['maxattachsize']:$uploadSetting['allow_upload_size'];
			$this->maxfetchwidth = $uploadSetting['fetch_image_size_w'];
			$this->maxfetchheight = $uploadSetting['fetch_image_size_h'];
			
			if($this->memperm['allowfileext']&&!$this->isadmin&&!$this->iseditor){
				$extension_whitelist = explode('|', $this->memperm['allowfileext']);
				$exts = '';
				$exts_des = '';
				foreach ($extension_whitelist as $ext){
					$exts .= '*.'.$ext.';';
					$exts_des .= strtoupper($ext).' Files; ';
				}
				$this->allowtype = $exts;
				$this->allowtype_desc = $exts_des;
			}else{
				$this->allowtype = $uploadSetting['allow_upload_type_swf'];
				$this->allowtype_desc = $uploadSetting['allow_upload_type_swf_desc'];
			}

			$this->allowvideo = ($this->memperm['allowvideo']||$this->isadmin||$this->iseditor);
			$this->allowfetch = ($this->memperm['allowfetch']||$this->isadmin||$this->iseditor);
			$this->shareSetting = $api->getSetting('share');
			$this->uploadToken = random(10);
			$this->sessionput('uploadToken', $this->uploadToken);
			$this->attaches = load_api('attachment')->findAttachByItem($this->share['item_id']);
			$this->intro = load_api('puzzcode')->parse_message($this->share['intro'],$this->attaches,true);
			$this->output('share/edit');
			return;
		}


		$this->ajax_failed_response(lang('500_operatefaild','tip'));
	}


	public function delete(){
		$share_id = $this->param('sid');
		$shareapi = load_api('share');
		if($share_id){
			$share = $shareapi->getShareById($share_id);
		}
		if($share){
			if(!$this->iseditor&&!$this->isadmin&&$share['user_id'] != $this->cuser['uid']){
				$this->ajax_failed_response(lang('illegal_operation','tip'));
				return;
			}
			$shareapi->deleteShareById($share_id);
			$this->ajax_success_response(array('jsfunc'=>'afterDeleteShare','share_id'=>$share_id),lang('200_operatesuccess','tip'));
			return;
		}
		$this->ajax_failed_response(lang('500_operatefaild','tip'));
		return;
	}

	public function addlike(){
		$share_id = $this->param('sid');
		$shareapi = load_api('share');
		$result = $shareapi->addlike($share_id,$this->cuser['uid']);
		if($result===true){
			$this->ajax_success_response(null);
		}else{
			$this->ajax_failed_response($result);
		}
	}

	public function removelike(){
		$share_id = $this->param('sid');
		$shareapi = load_api('share');
		$result = $shareapi->removelike($share_id,$this->cuser['uid']);
		if($result===true){
			$this->ajax_success_response(null);
		}else{
			$this->ajax_failed_response($result);
		}
	}
	
	public function dtype(){
		if(!$this->isadmin&&!$this->iseditor){
			$this->ajax_failed_response(lang('nopermission','tip'));
			return;
		}

		$share_id = $this->param('sid');
		$type = $this->param('type');
		$lt = $this->param('lt');
		$shareapi = load_api('share');
		$share = $shareapi->getShareById($share_id);
		if($share){
			if($type=='digist'&&$result = $shareapi->digist($share_id,$lt)){
				if($lt=='g'){
					load_api('event')->digist($share['user_id'],$share['title'],$share_id,$share['user_id']);
				}
			}else if($type=='maketop'&&$result = $shareapi->maketop($share_id,$lt)){
				if($lt=='g'||$lt=='c'){
					load_api('event')->top($share['user_id'],$share['title'],$share_id,$share['user_id']);
				}
			}
		}

		if ($result) {
			$this->ajax_success_response(array('jsfunc'=>'afterDtypeShare','share_id'=>$share_id,'type'=>$type,'lt'=>$lt),lang('200_operatesuccess','tip'));
		}else{
			$this->ajax_failed_response(lang('500_operatefaild','tip'));
		}

	}

	public function collect(){
		if(!$this->sysperm['allowpost']){
			$this->message(lang('nopermission','tip'),lang('nopermission','tip'));
			return;
		}
		$images = $this->param("links");
		$rel = $this->param("rel");
		if($images){
			$this->images = unserialize(stripslashes($images));
		}
		$this->rel = $rel;
		$api = load_api('setting');
		$uploadSetting = $api->getSetting('upload');
		$this->allowmaxnum = ($this->memperm['maxattachnum']&&!$this->isadmin&&!$this->iseditor)?$this->memperm['maxattachnum']:$uploadSetting['allow_max_num'];
		$this->maxattachsize = ($this->memperm['maxattachsize']&&!$this->isadmin&&!$this->iseditor)?$this->memperm['maxattachsize']:$uploadSetting['allow_upload_size'];

		if($this->memperm['allowfileext']&&!$this->isadmin&&!$this->iseditor){
			$extension_whitelist = explode('|', $this->memperm['allowfileext']);
			$exts = '';
			$exts_des = '';
			foreach ($extension_whitelist as $ext){
				$exts .= '*.'.$ext.';';
				$exts_des .= strtoupper($ext).' Files; ';
			}
			$this->allowtype = $exts;
			$this->allowtype_desc = $exts_des;
		}else{
			$this->allowtype = $uploadSetting['allow_upload_type_swf'];
			$this->allowtype_desc = $uploadSetting['allow_upload_type_swf_desc'];
		}

		$this->allowvideo = ($this->memperm['allowvideo']||$this->isadmin||$this->iseditor);
		$this->allowfetch = ($this->memperm['allowfetch']||$this->isadmin||$this->iseditor);
		$this->shareSetting = $api->getSetting('share');
		$this->uploadToken = random(10);
		$this->sessionput('uploadToken', $this->uploadToken);
		$this->output("share/collect");
	}

	private function processuploadimgs($data){
		$return = false;
		if($data['uploadimgs']){
			$uploadimgs = unserialize(stripslashes($data['uploadimgs']));
			foreach ($uploadimgs as $img){
				$return['aids'][] = $aid = $img['aid'];
				$cover = $img['cover'];
				$desc = $img['desc'];
				$api = load_api('attachment');
				if($att = $api->moveToReal($aid,$data['item_id'],$desc,$cover)){
					if($cover&&!$return['findcover']){
						$return['findcover']=true;
						$return['attachment']=$att['attachment'];
						$return['fileext']=$att['fileext'];
						$return['item_type']='image';
						$return['share_type']='upload';
						$return['aid']=$aid;
						$return['width']=$att['width'];
						$return['height']=$att['height'];
					}
				}
			}
			$return['total'] = array_length($uploadimgs);
		}
		return $return;
	}

	private function processuploadfiles($data){
		$return = false;
		if($data['uploadfiles']){
			$uploadfiles = unserialize(stripslashes($data['uploadfiles']));
			foreach ($uploadfiles as $file){
				$return['aids'][] = $aid = $file['aid'];
				$cover = $file['cover'];
				$desc = $file['desc'];
					
				$api = load_api('attachment');
				$api->moveToReal($aid,$data['item_id'],$desc,$cover);
			}
			$return['findcover']=false;
			$return['total'] = array_length($uploadfiles);
		}
		return $return;
	}

	private function processuploadvideos($data){
		$return = false;
		if($data['videos']){
			$videos = unserialize(stripslashes($data['videos']));
			foreach ($videos as $v){
				$url = $v['url'];
				$image = $v['image'];
				$cover = $v['cover'];
				$desc = $v['desc'];
				$flv = $v['flv'];
					
				$api = load_api('attachment');
				if($att = $api->saveRemoteVideo($image,$flv,$url,$data['item_id'],$desc,$cover)){
					if($cover&&!$return['findcover']){
						$return['findcover']=true;
						$return['attachment']=$att['attachment'];
						$return['fileext']=$att['fileext'];
						$return['item_type']='video';
						$return['share_type']='web';
						//$return['reference_url']=$url;
						$return['aid']=$att['aid'];
						$return['color']='';
						$return['width']=$att['width'];
						$return['height']=$att['height'];
					}
					$return['aids'][] = $att['aid'];
					$return['remoteimgs'][] = $att;
				}
			}
			$return['total'] = array_length($fetchs);
		}
		return $return;
	}

	private function processfetchs($data){
		$return = false;
		if($data['fetchs']){
			$fetchs = unserialize(stripslashes($data['fetchs']));
			foreach ($fetchs as $img){
				$url = $img['url'];
				$image = $img['image'];
				$cover = $img['cover'];
				$desc = $img['desc'];
				$type = $img['type'];
				$prourl = $img['prourl'];
				$pitemid = $img['itemid'];
					
				$api = load_api('attachment');
				if($att = $api->saveRemoteImage($image,$url,$data['item_id'],$desc,$cover)){
					if($cover&&!$return['findcover']){
						$return['findcover']=true;
						$return['attachment']=$att['attachment'];
						$return['item_type']='image';
						$return['fileext']=$att['fileext'];
						$return['width']=$att['width'];
						$return['height']=$att['height'];
						$return['share_type']=$type;
						$return['pitemid']=$pitemid;
						$return['prourl']=$prourl;
						$return['aid']=$att['aid'];
					}
					$return['aids'][] = $att['aid'];
					$return['remoteimgs'][] = $att;
				}
			}
			$return['total'] = array_length($fetchs);
		}
		return $return;
	}

	private function prepareItem($postdata,$isedit=false){
		$puzzcode = load_api('puzzcode');
		$api = load_api('setting');

		$keyword = str_replace('  ', ' ', $postdata['keyword']);
		if($keyword){
			$keywordarr = explode(' ', $keyword);
			$keyword_search = encodekeywords($keywordarr);
		}
		$intro_search = $plaintxt = $puzzcode->parse_plain_message($postdata['text']);
		$setting = $api->getSetting('share');
		$tagnum = $setting['tagnum'];
		if($setting['verify']){
			$isshow = $this->sysperm['postverify']?'0':'1';
		}else{
			$isshow = '1';
		}
		$nowtagnum = array_length(explode(' ', $keyword));
		if($nowtagnum<$tagnum){
			$tagapi = load_api('tag');
			$collected = $tagapi->collectFromTxt($postdata['category_id'],$postdata['title'].$plaintxt,$tagnum-$nowtagnum);
			if($collected['tag']) $collected_tag = join(' ', $collected['tag']);
			if($collected['search']) $collected_search = join(' ', $collected['search']);
			$keyword .= ' '.$collected_tag;
			$keyword_search .= ' '.$collected_search;
			$keyword = str_replace('  ', ' ', $keyword);
		}

		//$keyword_search = $keyword;
		if($this->isChineseVersion()){
			$segment = &load_class('Segment');
			//$keyword_search = $segment->convert_to_py($keyword_search);
			$segdb = $segment->getDbData($plaintxt);
			$keyword_search .= ' '.$segdb['keywordSearch'];

			$segment_str = $segment->segment($plaintxt);
			$intro_search = $segment_str['py'];
		}

		$parseat_str = $puzzcode->parse_at($postdata['text']);
		$parsetopic_str = $puzzcode->parse_topic($parseat_str['message']);
		if(!$isedit){
			$user = $this->cuser;
			$data['user_id']=$user['uid'];
			$data['user_nickname']=$user['nickname'];
		}
		$data['title'] = isset($postdata['title']) ? dhtmlspecialchars(trim($postdata['title'])) : '';
		$data['title'] = !empty($data['title']) ? delete_html(str_replace("\t", ' ', $data['title'])) : $data['title'];
		$data['keyword']=$keyword;
		$data['keyword_search']=$keyword_search.' '.$parseat_str['atsearch_str'].' '.$parsetopic_str['search_str'];
		$data['color']='';
		$data['image_path_0']='';
		$data['image_path_1']='';
		$data['image_path_2']='';
		$data['width']='';
		$data['height']='';
		$data['item_type']='';
		$data['share_type']='';
		$data['price']=$postdata['price'];
		$data['is_show']=$isshow;
		$data['total_images']='';
		$data['summary']=sysSubStr($plaintxt, 500, TRUE);

		$datadetail['intro']=$parsetopic_str['message'];
		$datadetail['intro_search']=$intro_search.' '.$parseat_str['atsearch_str'].' '.$parsetopic_str['search_str'];
		$datadetail['reference_url']=$postdata['url'];
		$datadetail['reference_itemid']='';
		$datadetail['promotion_url']='';

		if(!$isedit){
			$datashare['poster_id']=$user['uid'];
			$datashare['poster_nickname']=$user['nickname'];
			$datashare['user_id']=$user['uid'];
			$datashare['user_nickname']=$user['nickname'];
		}
		$datashare['category_id']=$postdata['category_id'];
		$datashare['album_id']=$postdata['album_id'];

		if($groupid = $this->param("groupid")){
			$this->group = load_db("group")->find_one(array('group_id'=>$groupid));
			if($this->group){
				$datadetail['intro_search'] .= ' group'.$groupid.'g';
				$data['keyword_search'] .= ' group'.$groupid.'g';
			}
		}

		if($storeid = $this->param("storeid")){
			$this->store = load_db("store")->find(array('store_id'=>$storeid));
			if($this->store){
				$datashare['store_id']=$storeid;
				$datashare['channel']=$this->param("storechannel",'review');
			}
		}

		$data['itemdetail'] = $datadetail;
		$data['sharedata'] = $datashare;

		$shareapi = load_api('share');
		if($isedit){
			return $shareapi->updateOriginalShare($postdata,$data)?$data:false;
		}else{
			return $shareapi->addOriginalShare($data);
		}
	}

	public function post(){
		if(!$this->sysperm['allowpost']){
			$this->message(lang('nopermission','tip'),lang('nopermission','tip'));
			return;
		}
		$api = load_api('setting');
		$act=$this->param('act');
		if($act=='save'){
			$data = array();
			$requiredParam = array('title','text','category_id','album_id');

			$shareSetting = $this->shareSetting;
			$titleminlenth=$shareSetting['title_range_s']?$shareSetting['title_range_s']:4;
			$titlemaxlength=$shareSetting['title_range_l']?$shareSetting['title_range_l']:100;

			$contentmaxlenth=$shareSetting['content_range_l']?$shareSetting['content_range_l']:10000;
			$fvalidation = load_class('Form_validation');
			foreach ($requiredParam as $rkey){
				if($rkey=='title'){
					$fvalidation->set_rules($rkey, 'lang:'.$rkey.':field' , 'trim|required|min_length['.$titleminlenth.']|max_length['.$titlemaxlength.']|xss_clean');
				}elseif($rkey=='text'){
					$fvalidation->set_rules($rkey, 'lang:'.$rkey.':field' , 'trim|max_length['.$contentmaxlenth.']|xss_clean');
				}else{
					$fvalidation->set_rules($rkey, 'lang:'.$rkey.':field' , 'trim|required|xss_clean');
				}
				$data[$rkey] = $this->param($rkey);
			}
			if ($fvalidation->run() == FALSE){
				$this->ajax_failed_response($fvalidation->error_string());
				return FALSE;
			}

			$optionalParam = array('price','keyword','url');
			foreach ($optionalParam as $okey){
				$data[$okey] = $this->param($okey);
			}
			$optionalParam = array('uploadimgs','uploadfiles','videos','fetchs');
			foreach ($optionalParam as $okey){
				$data[$okey] = $this->param($okey,'',false);
			}

			$censorapi = load_api('censor');
			$txtresult = $censorapi->censor($data['text'],'***');
			if($txtresult){
				$this->ajax_failed_response($txtresult);
				return;
			}
			$titleresult = $censorapi->censor($data['title'],'***');
			if($titleresult){
				$this->ajax_failed_response($titleresult);
				return;
			}
			if($itemid = $this->prepareItem($data)){
				$data['item_id'] = $itemid;
				$results = array();
				$results[] = $this->processuploadimgs($data);
				$results[] = $this->processuploadfiles($data);
				$results[] = $this->processuploadvideos($data);
				$results[] = $fetchs = $this->processfetchs($data);
				$cover = array();
				$total = 0;
				foreach ($results as $r){
					$total += $r['total'];
					if($r['findcover']){
						$cover = $r;
					}
				}
				$cover['total'] = $total;
				if($fetchs['total']>0){
					$cover['remoteimgs'] = $fetchs['remoteimgs'];
				}
				if(load_api('share')->updateItem($cover, $itemid)){
					load_api('event')->afterpostshare($this->cuser['uid'],$data['title'],$itemid);
					load_api('attachment')->deleteUnusedByUser($this->cuser['uid']);
					load_api('album')->update_album_cover($data['album_id']);
				}
				load_db('user')->add_share($this->cuser['uid']);
				$topicid = $this->param("topicid");
				$redirect = $topicid?site_url('topic/show?topicid='.$topicid):site_url('pin/index?cat='.$data['category_id']);
				if($storeid=$this->param("storeid")){
					$act = $this->param("storechannel");
					$redirect = site_url('store/'.$act.'?storeid='.$storeid);
				}
				$this->ajax_success_response(array('url'=>$redirect),lang('200_postsuccess','tip'));
				return;
			}
			$this->ajax_failed_response(lang('500_postfaild','tip'));
			return;
		}else{
			if($topicid = $this->param("topicid")){
				$topic = load_db("topic")->find_one(array('topic_id'=>$topicid));
				$this->inittxt = '#'.$topic['topic_title'].'#';
				$this->topicid = $topicid;
			}
			if($groupid = $this->param("groupid")){
				$this->group = load_db("group")->find_one(array('group_id'=>$groupid));
				if($this->group) $this->groupid = $groupid;
			}
			if($storeid =  $this->param("storeid")){
				$this->store = load_api("store")->getStoreById($storeid);
				if($this->store) $this->storeid = $storeid;
				$this->storechannel = $this->param("storechannel",'review');
			}
			$uploadSetting = $api->getSetting('upload');
			$this->allowmaxnum = ($this->memperm['maxattachnum']&&!$this->isadmin&&!$this->iseditor)?$this->memperm['maxattachnum']:$uploadSetting['allow_max_num'];
			$this->maxattachsize = ($this->memperm['maxattachsize']&&!$this->isadmin&&!$this->iseditor)?$this->memperm['maxattachsize']:$uploadSetting['allow_upload_size'];
			$this->maxfetchwidth = $uploadSetting['fetch_image_size_w'];
			$this->maxfetchheight = $uploadSetting['fetch_image_size_h'];
			
			if($this->memperm['allowfileext']&&!$this->isadmin&&!$this->iseditor){
				$extension_whitelist = explode('|', $this->memperm['allowfileext']);
				$exts = '';
				$exts_des = '';
				foreach ($extension_whitelist as $ext){
					$exts .= '*.'.$ext.';';
					$exts_des .= strtoupper($ext).' Files; ';
				}
				$this->allowtype = $exts;
				$this->allowtype_desc = $exts_des;
			}else{
				$this->allowtype = $uploadSetting['allow_upload_type_swf'];
				$this->allowtype_desc = $uploadSetting['allow_upload_type_swf_desc'];
			}

			$this->allowvideo = ($this->memperm['allowvideo']||$this->isadmin||$this->iseditor);
			$this->allowfetch = ($this->memperm['allowfetch']||$this->isadmin||$this->iseditor);
			$this->uploadToken = random(10);
			$this->sessionput('uploadToken', $this->uploadToken);
			$this->output('share/post');
		}
	}
}